package io.adrainty.bolee.framework.gateway.utils;

import io.adrainty.bolee.framework.commons.basic.ResponseCode;
import io.adrainty.bolee.framework.commons.basic.ResultDTO;
import io.adrainty.bolee.framework.commons.utils.JsonUtil;
import io.adrainty.bolee.framework.commons.utils.ResultDTOUtil;
import io.netty.util.CharsetUtil;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/28 上午1:08
 */
public class ResponseHelper {

    private ResponseHelper() {}

    public static Mono<Void> writeFailed(ServerHttpResponse response, ResponseCode r){
        return writeFailed(response, r, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public static Mono<Void> writeFailed(ServerHttpResponse response, ResponseCode r, HttpStatusCode statusCode){
        // 应答状态
        response.setStatusCode(statusCode);
        // 响应格式
        response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        response.getHeaders().set("Cache-Control", "no-cache");
        // 返回结果封装
        ResultDTO<Boolean> responseWrap = ResultDTOUtil.error(r);
        String result = JsonUtil.toJson(responseWrap);
        DataBuffer buffer = response.bufferFactory().wrap(result.getBytes(CharsetUtil.UTF_8));
        //写入响应结果
        return response.writeWith(Mono.just(buffer)).doOnError(error -> DataBufferUtils.release(buffer));
    }

}
